<?php

namespace app\common\command;

use addons\shopro\service\Wallet as WalletService;
use app\common\model\shopro\UserNormalPrizeLogModel;
use app\common\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\exception\HttpResponseException;

class Normalgamewater extends Command
{
    protected function configure()
    {
        $this->setName('normalgamewater')->setHelp('普通会员游戏流水分佣')->setDescription('普通会员游戏流水分佣');
    }

    protected function execute(Input $input, Output $output)
    {
        $prizeLogModel = new UserNormalPrizeLogModel();
        $data = $prizeLogModel->with(['prize'])->where('status','<',2)->select();
        if ($data) {
            Db::startTrans();
            try {
                foreach ($data as $k=>$v){
                    if(!$v->prize || $v->prize->type == 1){
                        $v->status = 2;
                    }else{
                        //质押
                        $userInfo = User::where(['id'=>$v->user_id])->find();
                        if($userInfo){
                            $user_money     = $v->prize->num;
                            $v->status      = 1;
                            $draw_user_info = User::where('id','=',$v->draw_user_id)->where('level','>',0)->find();
                            if($draw_user_info){
                                $v->status      = 2;
                            }
                            $all_has_return = bcadd($v->has_return, $user_money);

                            if($all_has_return > $v->prize->money){
                                $user_money = $v->prize->money - $v->has_return;
                                $v->status  = 2;
                            }
                            $user_money = bcmul($user_money, config('site.zhiya_bili')/100,2);
                            if($user_money > 0){
                                WalletService::change($v->user_id, 'score', $user_money, 'team_prize', $v->id,
                                    '抽中'.$v->prize->title.'奖品返利');
                            }
                            $v->has_return = $user_money;
                        }else{
                            $v->status = 2;
                        }
                        $v->save();
                    }

                }
                Db::commit();
                echo '执行成功';
            } catch (HttpResponseException $e) {
                Db::rollback();
                $data    = $e->getResponse()->getData();
                $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                dump($message);
//                format_log_error($e, 'Rebatemoney.HttpResponseException', $message);
            }
        }else{
            echo "无数据";
        }
    }

}
